# _*_ coding:utf-8 _*_
# @Time  : 2023.05.18
# @Author: zizlee
from fastapi import APIRouter, Query, Body, Depends
from db_utils import BaseDatabaseConnection
from utils.jwt_token import QuietTokenPayload
from response import APIResponse
from constant.section_scope import SectionScope
from constant.user import UserType
from constant.message import PeriodReportConstant
from constant.variety import VarietyConstants, AliasVariety
from settings import FILE_STORAGE_HOST, STATIC_HOST


class PeriodReport:
    ICONS = {
        'DOCX': 'doc-file',
        'DOC': 'doc-file',
        'PDF': 'pdf-file',
    }

    def __init__(self, ft: str = None, variety_en: str = None, user_id: int = None, user_type: int = None):
        self.file_type = ft  # 报告类型
        self.variety_en = variety_en  # 所属品种
        self.user_id = user_id  # 查询报告的用户
        self.user_type = user_type

    def pagination_list(self, kw: str = None, page: int = 1, page_size: int = 50):
        alias_variety = AliasVariety()
        if self.variety_en:
            self.variety_en = alias_variety.report_alias(self.variety_en)  # 前端传来的品种转为后端数据库标准

        # 1.默认全品种查询SQL
        a_sql = "SELECT id,file_date,variety_en,title,filepath,file_type,suffix,is_location FROM infor_periodic_report WHERE is_active=1"
        a_prm = []
        if self.file_type and self.file_type in PeriodReportConstant.CATEGORIES.keys():
            a_sql += " AND file_type=%s"
            a_prm.append(self.file_type)
        if self.variety_en:
            a_sql += " AND FIND_IN_SET(%s,variety_en)"
            a_prm.append(self.variety_en)
        if kw:
            a_sql += " AND title LIKE %s"
            a_prm.append(f'%{kw}%')

        # 2.需要监测品种权限的SQL
        b_sql = """
            SELECT a.id,a.file_date,a.variety_en,a.title,a.filepath,a.file_type,a.suffix
            FROM infor_periodic_report AS a
            INNER JOIN ruizhi_user_section_variety as b on FIND_IN_SET(b.variety_en,a.variety_en)
            WHERE b.sec_key='SEC001' AND b.`expire_date`>CURDATE()
        """
        b_prm = []
        if self.file_type and self.file_type in PeriodReportConstant.CATEGORIES.keys():
            b_sql += " AND a.file_type=%s"
            b_prm.append(self.file_type)
        if self.variety_en:
            b_sql += " AND FIND_IN_SET(%s,a.variety_en)"
            b_prm.append(self.variety_en)
        if kw:
            b_sql += " AND a.title LIKE %s"
            b_prm.append(f'%{kw}%')

        if self.user_id:  # 登录用户
            a_sql += " ORDER BY file_date DESC,create_time DESC;"
            b_sql += " ORDER BY file_date DESC,create_time DESC;"
        else:  # 未登录情况未首页，按热度排序，只获取第一页
            a_sql += " ORDER BY reading DESC;"
            b_sql += " ORDER BY reading DESC;"
            page = 1  # 未登录只能获取第一页

        # print(sql)
        # print(prm)
        sql = a_sql
        prm = a_prm
        with BaseDatabaseConnection() as conn:
            if self.user_type in UserType.VARIETY_AUTH_SETS:
                # 查询用户是不是全品种
                conn.cursor.execute("SELECT id FROM ruizhi_user_section_variety WHERE sec_key=%s AND variety_en='VAR_ALL' AND user_id=%s AND expire_date>=CURDATE() LIMIT 1;",
                                    [SectionScope.INFOR_REPORT_KEY, self.user_id])
                all_access = conn.cursor.fetchone()
                if not all_access:
                    sql = b_sql
                    prm = b_prm
            ret = conn.query_paginator(sql, param=prm, page=page, page_size=page_size)

        for row in ret['rows']:
            if row['is_location']:  # 存在本系统的静态文件中
                row['pdf_file'] = STATIC_HOST + row['filepath']
            else:
                row['pdf_file'] = FILE_STORAGE_HOST + row['filepath']

            real_ven = alias_variety.report_alias_reverse(row['variety_en'])  # 数据库内的品种代码转为前端标准
            row['variety_name'] = VarietyConstants.get_variety_name(real_ven)

            if row['file_type'] == 'TECHNICAL':
                row['variety_name'] = ','.join([VarietyConstants.get_variety_name(v) for v in row['variety_en'].split(',')])

            row['file_type_name'] = PeriodReportConstant.report_category(row['file_type'])

            row['file_icon'] = self.ICONS.get(row['suffix'])
        return APIResponse.success(data=ret)

    def report_info(self, rid: int):
        with BaseDatabaseConnection() as conn:
            conn.cursor.execute('SELECT id,file_date,title,filepath,suffix FROM infor_periodic_report WHERE id=%s LIMIT 1;',
                                [rid])
            report = conn.cursor.fetchone()
        if report:
            report['file_url'] = FILE_STORAGE_HOST + report['filepath']
        return APIResponse.success(data={'data': report})

    def get_report_paginator(self, page: int, page_size: int):
        sql = "SELECT id,file_date,title,filepath,file_type,suffix,is_location FROM infor_periodic_report WHERE is_active=1"
        prm = []
        if self.file_type and self.file_type in PeriodReportConstant.CATEGORIES.keys():
            sql += ' AND file_type=%s'
            prm.append(self.file_type)
        if self.variety_en:
            sql += ' AND variety_en=%s'
            prm.append(self.variety_en)
        sql += ' ORDER BY file_date DESC,create_time DESC;'
        with BaseDatabaseConnection() as conn:
            ret = conn.query_paginator(sql, prm, page=page, page_size=page_size)
        for row in ret['rows']:
            if row['is_location']:  # 存在本系统的静态文件中
                row['pdf_file'] = STATIC_HOST + row['filepath']
            else:
                row['pdf_file'] = FILE_STORAGE_HOST + row['filepath']
            row['file_icon'] = self.ICONS.get(row['suffix'])
        return APIResponse.success(data=ret)

    def reading_count(self, rid: int):
        with BaseDatabaseConnection() as conn:
            conn.cursor.execute("UPDATE infor_periodic_report SET reading=reading+1 WHERE id=%s;", (rid, ))
        return APIResponse.success()


period_report_api = APIRouter()


@period_report_api.get('/')  # 查询报告列表
def report_pagination_list(
        user: QuietTokenPayload = Depends(QuietTokenPayload),
        ft: str = Query(None),
        kw: str = Query(None),
        ven: str = Query(None),
        page: int = Query(1),
        page_size: int = Query(50)
):
    return PeriodReport(ft=ft, variety_en=ven, user_id=user.user_id(), user_type=user.user_type()).pagination_list(
        kw=kw, page=page, page_size=page_size
    )


@period_report_api.get('/info/')
def get_report_info(rid: int = Query(...)):
    return PeriodReport().report_info(rid=rid)


@period_report_api.get('/paginator/')  # 分页获取最新报告(首页)
def get_reports(page: int = Query(1), page_size: int = Query(50), ft: str = Query(None), ven: str = Query(None)):
    return PeriodReport(ft=ft, variety_en=ven).get_report_paginator(page=page, page_size=page_size)


@period_report_api.post('/reading/')  # 报告的阅读量
def update_report_reading(rid: int = Body(embed=True)):
    return PeriodReport().reading_count(rid=rid)
